// map存储
// 主要思路是先把数据转成Map去存储，之后遍历的同时借助对象的引用，直接从Map找对应的数据做存储

let arr = [
    {id: 1, name: '1', pid: 0},
    {id: 2, name: '2', pid: 1},
    {id: 3, name: '3', pid: 1},
    {id: 4, name: '4', pid: 3},
    {id: 5, name: '5', pid: 3},
   ]

function transfer(items) {
    const result = []
    const map = {}

    // 先转成map存储
    for(const item of items) {
        map[item.id] = {...item, children:[]}
    }

    for(const item of items) {
        const id = item.id
        const pid = item.pid
        const treeItem = map[id]
        if(pid == 0) {
            result.push(treeItem)
        }
        else{
            if(!map[pid]) {
                map[id] = {
                    children:[]
                }
            }
            else {
                map[pid].children.push(treeItem)
            }
        }
    }
    return result
}

console.log(transfer(arr))